<?php

namespace StudyBuddy\Modules\Blogger;

/**
 *
 * Class for parsing (extracting) array
 * of all blogs that user has with Blogger
 * The input xml file is returned from Blogger API
 * as result to call to this url: https://www.blogger.com/feeds/default/blogs
 * by an authenticated user
 * We usually call this url during the "connect blogger" process
 * right after the user just authorized blogger account via OAuth
 *
 */
class Blogs {

    /**
     *
     * Parse $xml and return array of blogs
     * each element in that array is an array
     * with keys: 'id', 'title' and 'url'
     *
     * @param string $xml xml returned by Blogger API
     * in response to request https://www.blogger.com/feeds/default/blogs
     * by an authenticated user (using OAuth credentials)
     *
     * @throws \Exception
     */
    public function getBlogs($xml) {

        $aBlogs = array();
        $XML = new \StudyBuddy\Dom\Document();
        if (false === $XML->loadXML($xml)) {
            $err = 'Unexpected Error parsing response XML';
            throw new \Exception($err);
        }

        $xp = new \DOMXPath($XML);
        $xp->registerNamespace('atom', "http://www.w3.org/2005/Atom");

        $aParsed = $XML->getElementsByTagName('entry');

        if (0 === $aParsed->length) {
            e('Looks like user does not have any blogs: $xml: ' . $xml);

            $err = ('Looks like you have Blogger account but do not have any blogs setup yet');
            throw new \Exception($err);
        }

        foreach ($aParsed as $blog) {
            $aBlog = array();
            $aBlog['id'] = $this->getId($blog);
            $aBlog['title'] = $blog->getElementsByTagName('title')->item(0)->nodeValue;
            $r = $xp->query('atom:link[@type = "text/html"]/@href', $blog);
            $aBlog['url'] = ($r->length > 0) ? $r->item(0)->nodeValue : null;
            if (!empty($aBlog['url']) && !empty($aBlog['id'])) {
                $aBlogs[] = $aBlog;
            }
        }

        return $aBlogs;
    }

    /**
     * Extract value of actual blog ID
     * from the 'id' tag
     * the value looks like this:
     * <id>tag:blogger.com,1999:user-850590157766.blog-4083976222769752292</id>
     * we need only the numeric value after the id-
     *
     * @param \DOMElement $el
     * @return mixed null if not found | string numeric value
     */
    public function getId(\DOMElement $el) {
        $a = $el->getElementsByTagName('id');
        if (0 === $a->length) {
            return null;
        }

        $val = $a->item(0)->nodeValue;
        $pos = \strrpos($val, '-');

        return (!$pos) ? null : \trim(\substr($val, ($pos + 1)));
    }

}
